package com.bright.ghj.overt.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author hxj
 * @Date 2025/5/6 16:22
 * @Description
 */
public class DockingUtil {

    public static boolean checkTimestamp(Date timestampDate) {
        Calendar timestampCal = Calendar.getInstance();
        timestampCal.setTime(timestampDate);
        // 由于我们服务器上时间不与网络同步 改成正负5分钟内都正确
        Calendar earliestCal = Calendar.getInstance();
        earliestCal.add(Calendar.MINUTE, -5);
        Calendar latestCal = Calendar.getInstance();
        latestCal.add(Calendar.MINUTE, 5);
        return timestampCal.compareTo(earliestCal) > 0 && timestampCal.compareTo(latestCal) <= 0;
    }

    public static String getSign(String appSecret, String nonce, String timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
        String content = "appSecret="+appSecret+"&nonce="+nonce+"&timestamp="+timestamp;
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        byte[] keyBytes = appSecret.getBytes(StandardCharsets.UTF_8);
        hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, "HmacSHA256"));
        return new String(Base64.encodeBase64(hmacSha256.doFinal(content.getBytes(StandardCharsets.UTF_8)), false));
    }
}
